const express = require('express')
const jwt = require('jsonwebtoken')
const AdminUser = require('../db/model/adminUser')
const assert = require('http-assert')
const bcrypt = require('bcrypt')
const { auth } = require('../middlewares/auth')
const { SuccessModel } = require('../utils/resModel')
const router = express.Router()

router.get('/auth', auth, async (req, res) => {
  res.json(new SuccessModel())
})

/**
 * 登录
 */
router.post('/login', async (req, res) => {
  const { username, password } = req.body
  const user = await AdminUser.findOne({ username: username }).select({ password: 1 })
  assert(user, 404, '当前用户不存在')
  const ifPassWordTrue = bcrypt.compareSync(password, user.password)
  assert(ifPassWordTrue, 400, '密码不正确')
  const token = jwt.sign(
    {
      id: user._id
    },
    process.env.SECRET
  )
  res.json(new SuccessModel({ token: token }, '登录成功'))
})

/**
 * 注册后台账号
 */
router.post('/register', async (req, res) => {
  const { username, password } = req.body
  const user = new AdminUser({
    username: username,
    password: password
  })
  const info = await user.save()
  assert(info, 400, '注册失败')
  const token = jwt.sign(
    {
      id: user._id
    },
    process.env.SECRET
  )
  const data = new SuccessModel({ token: token }, '注册成功')
  res.json(data)
})

module.exports = router
